package vn.vfriends.vbox.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.inject.Inject;
import vn.vfriends.vbox.model.Account;
import vn.vfriends.vbox.service.AccountService;

/**
 *
 * @author tuancn
 */
@FacesConverter(value = "accountConverter")
public class AccountConverter implements Converter {
    
    @Inject
    private AccountService accountService;
    
    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String name) {
        if (name == null || name.length() == 0) {
            return null;
        }
        Integer userId = (Integer)component.getAttributes().get("userId");
        return accountService.findByName(userId, name);
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
        if (object == null) {
            return null;
        }
        if (object instanceof Account) {
            Account account = (Account) object;
            return account.getName();
        } else {
            throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: vn.vfriends.vbox.model.Account");
        }
    }
}
